/** ****************************************************************************
 * CopyRight (C) 2012 Sharadendu Sinha.
 * Licensing : FreeBSD 
 *
 * @(#) $Id$
 */
package com.sps.test.signalling;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import com.sps.signalling.SignallingEntity;
import com.sps.signalling.Slot;
//This is the slot provider entity
public class TimerUI implements ActionListener
{
	private final static long diff = 10;
	private JPanel panel = new JPanel();
	// this is the signal emmitting entity
	private Timer timer = new Timer(diff);
	private final static String CMD_START = "START";
	private final static String CMD_STOP = "STOP";
	private JLabel lblTick = new JLabel(" ");
	private final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss - SSS");
	private final Date date = new Date(0);
	
	private final SignallingEntity signallingEntity = new SignallingEntity();
		
	public TimerUI()
	{
		// Here slot gets connected to signal
		timer.getSignallingEntity().connect(Timer.SIGNAL_TIMER_TICK, new Slot("SLOT_TIMER_TICK" , signallingEntity, "timerTick" , new Class[]{int.class}, this));		
		panel.add(lblTick);
		JButton button = new JButton(CMD_START);
		button.addActionListener(this);
		panel.add(button);
		button = new JButton(CMD_STOP);
		button.addActionListener(this);
		panel.add(button);
		date.setTime(0);
		lblTick.setText(""+ dateFormat.format(date));
	}
	
	// This is the SLOT method
	public void timerTick(int tickCount)
	{
		System.out.println("tick :" + tickCount);
		date.setTime(tickCount * diff);
		lblTick.setText(""+ dateFormat.format(date));
	}
	
	@Override
	public void actionPerformed(ActionEvent ae)
	{
		if(CMD_START.equals(ae.getActionCommand()))
		{
			timer.start();
		}
		else if(CMD_STOP.equals(ae.getActionCommand()))
		{
			timer.stop();
		}
	}
	
	public void show()
	{
		JFrame frame = new JFrame();
		frame.add(panel);
		frame.setTitle("Timer Utility ");
		frame.addWindowListener(new WindowAdapter()
		{
			@Override
			public void windowClosing(WindowEvent e)
			{
				super.windowClosing(e);
				System.exit(0);
			}
		});
		frame.setBounds(100, 100, 400, 100);
		frame.setVisible(true);
	}
	
	public static void main(String[] args)
	{
		TimerUI timerUI = new TimerUI();
		timerUI.show();
	}
}
